package icedot.library.common.map;

import java.util.Calendar;


/**
 * 修正定位的经纬度
 * @author WorkDot
 *
 */
public class FixLocation
{
	private final static int 	s_checkNum = 10;
	private final static double s_maxM = 150;
	private LocationInfo		_firstPoint;		//认为正确的点.
	private LocationInfo		_secondPoint;		//备选的点
	private LocationInfo		_lastPoint;			//上一个点
	private boolean 			_enable;			//是否启用过滤
	private int 				_checkNum;
	
	public FixLocation()
	{
		_enable = true;
		_checkNum = 0;
	}
	
	public void setEnable(boolean enable)
	{
		_enable = enable;
	}
	
	public LocationInfo checkFix(LocationInfo info)
	{
		if(!_enable)
		{
			return info;
		}
		//如果定位的位置没有变化,返回的定位时间仍然是上次的时间,所以更新一下时间.
//		info.setTime(Calendar.getInstance().getTimeInMillis());
		if(info.getSatelliteNumber() > 0) //默认认为卫星定位是正确的
		{
			_firstPoint = info;
			_lastPoint = info;
			return info;
		}
		else   //不是卫星定位的点
		{
			if(_firstPoint == null)  //第一个不是GPS的点
			{
				_firstPoint = info;
				_lastPoint = info;
				_checkNum = 0;
				return info;
			}
			else if(_lastPoint != null) //firstPoint已经有值了,判断下是否漂移很严重
			{
				double len = info.getDistance(
						_lastPoint.getLatitude(), 
						_lastPoint.getLongitude());
				long es = (info.getTime() - _lastPoint.getTime()) / 1000;
				if(es == 0 || len == 0) //还是上一个点
				{
				    return info;
				}
				len = len / es;
				if(len > s_maxM)  //漂移很严重
				{
					if(_secondPoint == null)   //第一次偏移很大,忽略
					{
						_secondPoint = info;
						_lastPoint = _firstPoint;
						_lastPoint.setTime(info.getTime());	
						_checkNum = 0;
						return _firstPoint;
					}
					else   //上次偏移的点与这次的点比较是否偏移在这附近
					{
						len = info.getDistance(
								_secondPoint.getLatitude(), 
								_secondPoint.getLongitude());
						es = (info.getTime() - _lastPoint.getTime()) / 1000;
						len = len / es;
						if(len > s_maxM)  //偏移的点与记录的点都不匹配
						{
							_lastPoint = _firstPoint;
							_lastPoint.setTime(info.getTime());	
							_secondPoint = info;
							return _firstPoint;
						}
						else
						{
							_checkNum++;
							_secondPoint = info;
							if(_checkNum >= s_checkNum) //常时间定位在这里..
							{
								_firstPoint = info;
								_lastPoint = info;
								_secondPoint = null;
								return info;
							}
							else
							{
								_lastPoint = _firstPoint;
								_lastPoint.setTime(info.getTime());	
								_secondPoint = info;
								return _firstPoint;
							}
						}
					}
				}
				else
				{
					len = info.getDistance(
							_firstPoint.getLatitude(), 
							_firstPoint.getLongitude());
					_firstPoint = info;
					_lastPoint = info;
					return info;
				}	
			}
			else   //还没有确定出点是否正确
			{
				_firstPoint = info;
				_lastPoint = info;
				return info;
			}
		}
	}
}
